//
//  Date-Extension.swift
//  SwiftWB
//
//  Created by 远成物流 on 2017/6/28.
//
//

import Foundation

extension Date{
    //class:类方法
    static func createDateString(createAtStr : String) -> String{
        
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale(identifier: "en")
        
        //将字符串转Date
        guard let createDate = fmt.date(from: createAtStr) else{
            return ""
        }
        
        let nowDate = Date()
        
        //计算与当前时间的时间差
        let interval = nowDate.timeIntervalSince(createDate)
        
        if interval < 60{
            return "刚刚"
        }
        
        if interval < 60 * 60{
            return "\(interval / 60)分钟前"
        }
        
        if interval < 60 * 60 * 24{
            return "\(interval / 60 * 60)小时前"
        }
        
        //创建日历对象
        let calender = Calendar.current
        
        if calender.isDateInYesterday(createDate) {
            fmt.dateFormat = "昨天 HH:mm"
            return fmt.string(from: createDate)
        }
        
        //一年以内
        let cmps = (calender as NSCalendar).components(.year, from: createDate, to: nowDate, options: [])
        if cmps.year! < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            return fmt.string(from: createDate)
        }
        
        //超过一年
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        return fmt.string(from: createDate)
    }
}
